<!--
  功能：初始化功能描述
  作者：zichen-jiang
  邮箱：18307106535@163.com
  版本：v1.0.2
  修改内容：vue2.0初始化模板
  修改人员：zicheng-jiang
  修订时间：2020.10.01
  组件生成时间：2022年06月17日 14:37:14
-->
<template>
  <div class="person">
    <div class="person-box">
      <h4>个人资料</h4>
      <div class="person-body">
        <a-form :form="form" :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="用户名">
            <a-input
              v-decorator="['userName']"
              placeholder="请输入用户名"
              :disabled="subdisabled"
            />
          </a-form-item>
          <a-form-item label="性别">
            <a-select
              v-decorator="['sex']"
              placeholder="请选择性别"
              :disabled="subdisabled"
            >
              <a-select-option value="0">保密</a-select-option>
              <a-select-option value="1">男</a-select-option>
              <a-select-option value="2">女</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="出生年月">
            <a-date-picker
              v-decorator="['birth']"
              placeholder="请选择出生年月"
              style="width: 100%"
              @change="dateChange"
              :disabled="subdisabled"
            />
          </a-form-item>
          <a-form-item label="个人简介">
            <a-textarea
              v-decorator="['introduction']"
              placeholder="填写职业技能、擅长的事情、喜欢的事情等"
              :auto-size="{ minRows: 6, maxRows: 6 }"
              :disabled="subdisabled"
            />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 3, offset: 3 }">
            <a-button
              type="primary"
              @click="
                () => {
                  subdisabled = false;
                }
              "
              v-if="subdisabled"
              >修改资料</a-button
            >
            <a-button type="primary" @click="quxiao" v-if="!subdisabled">取消</a-button>
            <a-button
              type="primary"
              @click="handleSubmit"
              v-if="!subdisabled"
              style="margin-left: 10px"
              >保存修改</a-button
            >
          </a-form-item>
        </a-form>
        <div class="userimg">
          <div>
            <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :accept="fileAccept"
              :customRequest="uploadImg"
              :beforeUpload="beforeUpload"
            >
              <img v-if="imageUrl" :src="baseUrl + imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">修改头像</div>
              </div>
            </a-upload>
          </div>
          <p class="userimg-userName">
            <span>{{ userInfo.userName }}</span>
            <img
              class="userimg-userName-rz"
              src="@/assets/rz.png"
              alt
              v-if="userInfo.Administrator == '0' || userInfo.Administrator == '1'"
            />
            <span v-if="userInfo.Administrator == '0' || userInfo.Administrator == '1'">{{
              userInfo.Administrator == "0"
                ? "超级管理员"
                : userInfo.Administrator == "1"
                ? "管理员"
                : ""
            }}</span>
          </p>
          <p>{{ userInfo.createUserDate }} 加入</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
//import(导入)其他文件（如：组件，工具js，第三方插件js，json文件，图片文件等）
import { uploads } from "@/utils/upload";
import moment from "moment";
import EventBus from "@/utils/EventBus";
import { requset } from "@/api";
export default {
  name: "person",
  /**注册组件*/
  components: {},
  /**接受父组件传值*/
  props: {},
  data() {
    return {
      form: this.$form.createForm(this),
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      createBirth: "",
      loading: false,
      imageUrl: "",
      subdisabled: true,
      fileAccept: "image/gif, image/jpeg, image/jpg, image/png, image/svg",
    };
  },
  /**计算属性*/
  computed: {},
  /**监听data数据变化*/
  watch: {},
  /**创建组件时执行(有VM对象this)*/
  created() {},
  /**加载完组件时执行(主要预处理数据)*/
  mounted() {
    this.$nextTick(() => {
      this.form.setFieldsValue({
        userName: this.userInfo.userName,
        sex: this.userInfo.sex,
        birth: this.userInfo.birth,
        introduction: this.userInfo.introduction,
        birth: moment(this.userInfo.createBirth, "YYYY-MM-DD"),
      });
      this.imageUrl = this.userInfo.userImg;
    });
  },
  /**所有方法*/
  methods: {
    dateChange(date, datestring) {
      this.createBirth = datestring;
    },
    // 文件上传
    uploadImg(upload) {
      if (upload.file.size > 3000000) {
        this.$message.error("上传图片大小不得大于3MB");
        return;
      }
      this.loading = true;
      uploads("/uploadsFiles/uploads", upload.file, this.imageUrl).then((res) => {
        this.loading = false;
        if (res.data.code == 200) {
          this.imageUrl = res.data.imgUrl;
          this.userInfo.userImg = res.data.imgUrl;
          EventBus.$emit("userInfo", this.userInfo);
          let params = {
            userImg: res.data.imgUrl,
            phone: this.userInfo.phone,
            userId: this.userInfo.userId,
          };
          this.updateUser(params);
          localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //上传文件前校验
    beforeUpload(file) {
      const extension1 = file.name.split(".")[1] === "jpg";
      const extension2 = file.name.split(".")[1] === "jpeg";
      const extension3 = file.name.split(".")[1] === "png";
      const extension4 = file.name.split(".")[1] === "gif";
      const extension5 = file.name.split(".")[1] === "svg";
      if (!extension1 && !extension2 && !extension3 && !extension4 && !extension5) {
        this.$message.error("别乱选，好好上传图片，再乱选头给你打歪！");
      }
      return extension1 || extension2 || extension3 || extension4 || extension5;
    },
    // 修改用户头像
    updateUser(params) {
      requset("post", "/users/updateUserimg", params).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    quxiao() {
      this.subdisabled = true;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          userName: this.userInfo.userName,
          sex: this.userInfo.sex,
          birth: this.userInfo.birth,
          introduction: this.userInfo.introduction,
          birth: moment(this.userInfo.createBirth, "YYYY-MM-DD"),
        });
        this.imageUrl = this.userInfo.userImg;
      });
    },
    // 修改
    handleSubmit() {
      let birthDate = "";
      if (this.createBirth == "") {
        birthDate = this.form.getFieldValue("birth")._i.substring(0, 10);
      } else {
        birthDate = this.createBirth;
      }
      let params = {
        userName: this.form.getFieldValue("userName"),
        sex: this.form.getFieldValue("sex"),
        createBirth: birthDate,
        introduction: this.form.getFieldValue("introduction"),
        phone: this.userInfo.phone,
        userId: this.userInfo.userId,
      };
      requset("post", "/users/updateUserInfo", params).then((res) => {
        if (res.data.code == 200) {
          this.userInfo = res.data.data;
          localStorage.setItem("userInfo", JSON.stringify(res.data.data));
          this.$message.success(res.data.msg);
          this.subdisabled = true;
          this.createBirth = this.userInfo.createBirth;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
  },
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.person {
  width: 85%;
}

.person h4 {
  padding: 13px 0;
  font-size: 17px;
  font-weight: 700;
}
::v-deep .ant-form {
  width: 70%;
}
::v-deep .ant-form-item-control-wrapper {
  width: 80%;
}
.userimg {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.userimg-userName {
  display: flex;
}
.userimg-userName-rz {
  width: 20px;
  height: 20px;
  margin-left: 20px;
  margin-right: 3px;
}
.person-body {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.avatar-uploader img {
  width: 100px;
  height: 100px;
}
</style>
